package com.sunshine.demo.aspect;

import com.alibaba.fastjson.JSON;
import com.sunshine.demo.annotation.DoSomething;
import com.sunshine.demo.model.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author: sanglei
 * @date: 2018-11-01 14:46
 * @description:
 */
@Component
@Aspect
public class DoSomethingAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;
    //@Around("execution(* com.sunshine.demo.service.*.*(..))")
    //@Around("@annotation(com.sunshine.demo.annotation.DoSomething)")
    @Around("@annotation(doSomething)")
    public Object doAround(ProceedingJoinPoint pjp,DoSomething doSomething) {
        //Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        //DoSomething annotation = method.getAnnotation(DoSomething.class);
        Class withinType = pjp.getSourceLocation().getWithinType();
        String className = withinType.getName();
        String methodName = pjp.getSignature().getName();
        System.out.println(className);
        System.out.println(methodName);
        boolean needLog = doSomething.needLog();
        String id = getValue(doSomething.key(),pjp);
        String s = redisTemplate.opsForValue().get(doSomething.cacheName()+id);
        if(null!=s){
            System.out.println("从Redis中获取用户信息");
            return JSON.parseObject(s, User.class);
        }
        System.out.println("=======================方法执行前=======================");
        Object user = null;
        try {
            user = pjp.proceed();
        } catch (Throwable throwable) {
            if(needLog){
                System.out.println("系统异常"+throwable);
            }
        }
        if(null!=user) {
            redisTemplate.opsForValue().set(doSomething.cacheName()+id, JSON.toJSONString(user), 20, TimeUnit.SECONDS);
        }
        System.out.println("=======================方法执行后=======================");
        return user;
    }

    public String getValue(String key,ProceedingJoinPoint pjp){
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(method);
        Object[] args = pjp.getArgs();
        return SpelParser.getValue(key,parameterNames,args);
    }
}
